package service

import (
	"errors"
	"fmt"
	"gitee.com/kubage88/wf-deploy-plugin-javax/consts"
	"gitee.com/kubage88/wf-deploy-plugin-javax/util"
	"github.com/shirou/gopsutil/process"
	"runtime"
	"strings"
	"time"
)

type Javax struct {
}

func (j *Javax) getJavaName() string {
	osType := strings.ToLower(runtime.GOOS)
	if osType == "windows" {
		return "java.exe"
	}

	return "java"
}

func (j *Javax) buildAgrs(jar, options, environments string) []string {
	args := make([]string, 0)
	if options != "" {
		options = strings.ReplaceAll(options, "\"", consts.EMPTY)
		ops := strings.Split(options, ",")
		for _, o := range ops {
			if o != "" {
				args = append(args, "-D"+strings.ReplaceAll(o, consts.BLANK_SEPARATOR, consts.EMPTY))
			}
		}
	}

	args = append(args, "-jar", strings.ReplaceAll(jar, "\"", consts.EMPTY))

	if environments != "" {
		environments = strings.ReplaceAll(environments, "\"", consts.EMPTY)
		envs := strings.Split(environments, ",")
		for _, e := range envs {
			if e != "" {
				args = append(args, "--"+strings.ReplaceAll(e, consts.BLANK_SEPARATOR, consts.EMPTY))
			}
		}
	}

	return args
}

// PreStart 开启java服务前置方法
func (j *Javax) PreStart(jar, options, environments string) {

}

// PostStart 开启java服务的后置方法
func (j *Javax) PostStart(jar, options, environments string) {

}

// Start 开启java服务
func (j *Javax) Start(jar, options, environments string) (result error) {

	defer func() {
		if err := recover(); err != nil {
			result = errors.New(fmt.Sprint(err))
		}
	}()

	j.PreStart(jar, options, environments)
	args := j.buildAgrs(jar, options, environments)
	result = util.Exec(j.getJavaName(), args...)
	j.PostStart(jar, options, environments)

	return result
}

// Stop 结束java服务
func (j *Javax) Stop(jar, options, environments string) (result error) {

	defer func() {
		if err := recover(); err != nil {
			result = errors.New(fmt.Sprint(err))
		}
	}()

	pros, _ := process.Processes()
	for _, p := range pros {
		cmdline, err := p.Cmdline()
		if err != nil {
			continue
		}

		name, err := p.Name()
		if err != nil {
			continue
		}

		if name == j.getJavaName() && strings.Contains(cmdline, jar) {
			//fmt.Println(fmt.Sprintf("命中目标了~~【%s】", cmdline))
			err = p.Kill()
			continue
		}
	}

	return result
}

// Restart 重启java服务
func (j *Javax) Restart(jar, options, environments string) (result error) {

	defer func() {
		if err := recover(); err != nil {
			result = errors.New(fmt.Sprint(err))
		}
	}()

	err := j.Stop(jar, options, environments)
	if err != nil {
		return err
	}

	<-time.After(time.Second * 1)

	err = j.Start(jar, options, environments)
	if err != nil {
		return err
	}

	return result
}
